import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:frontend/models/briefItems.dart';
import 'package:frontend/reqs/requests.dart';
import 'package:frontend/states/NetState.dart';
import 'package:frontend/states/cartState.dart';
import 'package:provider/provider.dart';

import '../models/address.dart';
import '../models/global.dart';
import 'ItemPage.dart';

class CartPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CartPageState();
  }
}

class CartPageState extends State<CartPage> {
  Address? selectedAddress;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: const Text('购物车'),
      ),
      bottomNavigationBar: BottomAppBar(
          shape: const CircularNotchedRectangle(),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Text(
                "收货地址：${selectedAddress?.address ?? "未选择"}",
                style: TextStyle(
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              ElevatedButton(
                  onPressed: () {
                    setState(() {});
                  },
                  child: Row(
                    children: [Icon(Icons.refresh), Text('刷新')],
                  )),
              ElevatedButton(
                  onPressed: () async {
                    if (!Global.profile.isLogin) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('请先登录！'),
                        ),
                      );
                    } else {
                      bool? res = await _showModalBottomSheet(
                          await fetchCart(Global.profile.user!.id));
                      if (res != null) {
                        if (!Global.profile.isLogin) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('请先登录'),
                            ),
                          );
                        } else {
                          setState(() {});
                          checkOutAllInCart(Global.profile.user!.id,
                              selectedAddress!.address_id);
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('订单已提交'),
                            ),
                          );
                        }
                      }
                    }
                  },
                  child: Row(
                    children: [
                      Icon(Icons.shopping_cart_checkout_outlined),
                      Text('结算')
                    ],
                  )),
              SizedBox(
                width: 20,
              ),
              ElevatedButton(
                  onPressed: () {
                    if (!Global.profile.isLogin) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('请先登录！'),
                        ),
                      );
                    } else {
                      setState(() {});
                      clearCart(Global.profile.user!.id);
                    }
                  },
                  child: Row(
                    children: [Icon(Icons.clear), Text('清空购物车')],
                  ))
            ],
          )),
      body: Consumer<NetState>(builder: (context, netState, widget) {
        return FutureBuilder<BriefItems>(
          future: fetchCart(Global.profile.user!.id),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) {
                return Text(snapshot.error.toString());
                //return const Icon(Icons.error);
              } else {
                return GridView.count(
                    restorationId: 'grid_view_demo_grid_offset',
                    crossAxisCount: 4,
                    mainAxisSpacing: 8,
                    crossAxisSpacing: 8,
                    padding: const EdgeInsets.all(8),
                    childAspectRatio: 1,
                    children: snapshot.data!.items
                        .map((e) => ItemCard(
                              itemId: e.id,
                              image: Image.memory(e.img),
                              title: e.name,
                              price: e.price,
                              //itemId: e.id,
                            ))
                        .toList());
              }
            } else {
              // 请求未结束，显示loading
              return CircularProgressIndicator();
            }
          },
        );
      }),
    );
  }

  Future<bool?> _showModalBottomSheet(BriefItems items) {
    return showModalBottomSheet<bool>(
      context: context,
      builder: (BuildContext context) {
        return ListView(
          children: [
            Text("确认提交订单？",
                style: TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.w600,
                    fontSize: 32)),
            for (var item in items.items)
              Column(
                children: [
                  Text(item.name,
                      style: TextStyle(
                          color: Colors.grey,
                          fontWeight: FontWeight.w300,
                          fontSize: 16)),
                  Text("￥${item.price}",
                      style: TextStyle(
                          color: Colors.lightBlueAccent,
                          fontWeight: FontWeight.w200,
                          fontSize: 16)),
                ],
              ),
            FutureBuilder<List<Address>>(
                future: fetchAddresses(Global.profile.user!.id),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    if (snapshot.hasError) {
                      return Text(snapshot.error.toString());
                    }
                    return ListTile(
                      title: Text(selectedAddress != null
                          ? selectedAddress!.address
                          : '选择地址'),
                      trailing: PopupMenuButton<Address>(
                        padding: EdgeInsets.zero,
                        onSelected: (value) {
                          setState(() {
                            selectedAddress = value;
                          });
                          Navigator.of(context).pop();
                        },
                        itemBuilder: (context) => <PopupMenuItem<Address>>[
                          for (var address in snapshot.data!)
                            PopupMenuItem<Address>(
                              value: address,
                              child: Text(
                                "${address.tag} ${address.contact} ${address.address} ${address.phone_number}",
                              ),
                            ),
                        ],
                      ),
                    );
                  } else {
                    return CircularProgressIndicator();
                  }
                }),
            Text(
                '总价 ￥${items.items.fold(0, (previousValue, element) => previousValue + element.price)}',
                style: TextStyle(
                    color: Colors.lightBlueAccent,
                    fontWeight: FontWeight.w200,
                    fontSize: 16)),
            ElevatedButton(
                onPressed: () {
                  if (selectedAddress == null) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('请选择收货地址'),
                      ),
                    );
                  } else {
                    //Provider.of<NetState>(context).somethingChangedInBackend();
                    Navigator.of(context).pop(true);
                  }
                },
                child: Text("提交订单"))
          ],
        );
      },
    );
  }
}

class ItemCard extends StatefulWidget {
  final int itemId;
  final Image image;
  final String title;
  final int price;

  const ItemCard(
      {super.key,
      required this.itemId,
      required this.image,
      required this.title,
      required this.price});

  @override
  State<ItemCard> createState() => _ItemCardState();
}

class _ItemCardState extends State<ItemCard> {
  @override
  Widget build(BuildContext context) {
    return GridTile(
      footer: Material(
        color: Colors.transparent,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(bottom: Radius.circular(4)),
        ),
        clipBehavior: Clip.antiAlias,
        child: GridTileBar(
          backgroundColor: Colors.black45,
          title: Text('${widget.title} ￥${widget.price}'),
          subtitle: Row(
            children: [
              TextButton(
                  onPressed: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                ItemPage(itemId: widget.itemId)));
                  },
                  child: Text('详情')),
              TextButton(
                  onPressed: () {
                    if (!Global.profile.isLogin) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('请先登录'),
                        ),
                      );
                    } else {
                      delFromCart(Global.profile.user!.id, widget.itemId);
                      Provider.of<NetState>(context, listen: false)
                          .somethingChangedInBackend();

                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('物品已被移出购物车,刷新以更新'),
                        ),
                      );
                    }
                  },
                  child: const Text('移出')),
            ],
          ),
        ),
      ),
      child: widget.image,
    );
  }
}
